package org.example.strategy;

import java.io.File;
import java.io.RandomAccessFile;

public class HistoryStrategy implements EditorStrategy{
    private long number;
    public HistoryStrategy(long number){
        this.number = number;
    }
    @Override
    public void performAction() {
        File file = new File("session.log");
        if (file.exists()){
            try(RandomAccessFile randomAccessFile = new RandomAccessFile("session.log", "r")) {
                long fileLength = randomAccessFile.length();
                long pointer = fileLength - 3;

                int linesRead = 0;
                if (number < 0){
                    number = fileLength;
                }
                while (pointer >= 0 && linesRead < number) {
                    randomAccessFile.seek(pointer);
                    char c = (char) randomAccessFile.read();
                    if (c == '\n') {
                        // 从文件末尾找到换行符，表示找到一行
                        String line = randomAccessFile.readLine();
                        System.out.println(line);
                        linesRead++;
                    }
                    pointer--;
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("Error!session.log does not exist!");
        }
    }
}
